/*
 * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
 *
 * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

 #include <iostream>
#include <chrono>
#include "Util/onceToken.h"
#include "Util/TimeTicker.h"
#include "Poller/EventPoller.h"

using namespace std;
using namespace toolkit;

int main() {

    Ticker ticker0;
    int nextDelay0 = 50;
    std::shared_ptr<onceToken> token0 = std::make_shared<onceToken>(nullptr,[](){
        std::cout << "task 0 被取消，可以立即触发释放lambad表达式捕获的变量!" << std::endl;
    });

    auto tag0 = EventPollerPool::Instance().getPoller()->doDelayTask(nextDelay0, [&,token0]() {
        std::cout << "task 0(固定延时重复任务),预期休眠时间 :" << nextDelay0 << " 实际休眠时间" << ticker0.elapsedTime() << std::endl;
        ticker0.resetTime();
        return nextDelay0;
    });
    token0 = nullptr;

    Ticker ticker1;
    int nextDelay1 = 50;
    auto tag1 = EventPollerPool::Instance().getPoller()->doDelayTask(nextDelay1, [&]() {
        std::cout << "task 1(可变延时重复任务),预期休眠时间 :" << nextDelay1 << " 实际休眠时间" << ticker1.elapsedTime() << std::endl;;
        ticker1.resetTime();
        nextDelay1 += 1;
        return nextDelay1;
    });


    // ThreadPool pool(thread::hardware_concurrency(), ThreadPool::PRIORITY_HIGHEST, true);

    // //每个任务耗时3秒  [AUTO-TRANSLATED:c1b83e8e]
    // // Each task takes 3 seconds
    // auto task_second = 1;
    // //每个线程平均执行4次任务，总耗时应该为12秒  [AUTO-TRANSLATED:ceab38cc]
    // // Each thread executes 4 tasks on average, the total time should be 12 seconds
    // auto task_count = thread::hardware_concurrency() * 4;

    // semaphore sem;
    // vector<int> vec;
    // vec.resize(task_count);
    // Ticker ticker;
    // {
    //     //放在作用域中确保token引用次数减1  [AUTO-TRANSLATED:a81d2393]
    //     // Put it in a scope to ensure the token reference count is decremented
    //     auto token = std::make_shared<onceToken>(nullptr, [&]() {
    //         sem.post();
    //     });

    //     for (auto i = 0; i < task_count; ++i) {
    //         pool.async([token, i, task_second, &vec]() {
    //             std::this_thread::sleep_for(std::chrono::seconds(task_second)); //休眠三秒
    //             std::cout << "task " << i << " done!" << std::endl;
    //             vec[i] = i;
    //         });
    //     }
    // }

    // sem.wait();
    // std::cout << "all task done, used milliseconds:" << ticker.elapsedTime();

    // //打印执行结果  [AUTO-TRANSLATED:08995cc8]
    // // Print the execution result
    // for (auto i = 0; i < task_count; ++i) {
    //     std::cout << vec[i] << std::endl;
    // }
    // return 0;
}
